<template>
  <div>
    <a-row :gutter="20" style="padding:0 0 20px 0">
      <a-col :span="8">
        <a-input-search
          size="large"
          placeholder="请输入搜索内容"
          v-model="queryInfo.query"
          enter-button
          @search="getSearchUserList"
          allowClear
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" size="large" @click="addModalVisible = true"
          >添加用户</a-button
        >
      </a-col>
    </a-row>
    <!-- 添加用户对话框 -->
    <a-modal
      v-model="addModalVisible"
      title="添加用户信息"
      ok-text="确认"
      cancel-text="取消"
      @ok="addUser"
      @cancel="addModalClosed"
    >
      <a-form-model
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        labelAlign="left"
      >
        <a-form-model-item label="用户名称" prop="username">
          <a-input v-model="addForm.username" />
        </a-form-model-item>
        <a-form-model-item label="用户密码" prop="password">
          <a-input type="password" v-model="addForm.password" />
        </a-form-model-item>
        <a-form-model-item label="邮箱" prop="email">
          <a-input v-model="addForm.email" />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="mobile">
          <a-input v-model="addForm.mobile" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-table
      rowKey="id"
      :columns="columns"
      :data-source="userList"
      :pagination="pagination"
      bordered
    >
      <a slot="name" slot-scope="text">{{ text }}</a>
      <!-- 状态按钮 -->
      <a-switch
        slot="state"
        slot-scope="dataIndex, record"
        v-model="record.mg_state"
        @change="userStateChanged(record)"
      ></a-switch>
      <!-- 操作按钮 -->
      <template slot="operation" slot-scope="dataIndex, record">
        <!-- 编辑按钮 -->
        <a-button
          type="primary"
          icon="edit"
          style="margin:3px;width:45px;heigh:25px"
          @click="showEditModal(dataIndex)"
        >
        </a-button>
        <!-- 删除按钮 -->
        <a-button
          type="danger"
          icon="delete"
          style="margin:3px;width:45px;heigh:25px"
          @click="removeUserById(dataIndex)"
        >
        </a-button>
        <!-- 分配角色 -->
        <a-button
          icon="setting"
          style="margin:3px;background:#ffa400;color:#fff;width:45px;heigh:25px"
          @click="setRole(record)"
        >
        </a-button>
      </template>
    </a-table>
    <!-- 修改用户对话框 -->
    <a-modal
      title="修改用户信息"
      v-model="editModalVisible"
      @ok="editUserInfo"
      @cancel="editModalClosed"
    >
      <a-form-model
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="用户名称" prop="username">
          <a-input v-model="editForm.username" disabled />
        </a-form-model-item>
        <a-form-model-item label="邮箱" prop="email">
          <a-input v-model="editForm.email" />
        </a-form-model-item>
        <a-form-model-item label="手机" prop="mobile">
          <a-input v-model="editForm.mobile" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 分配角色的对话框 -->
    <a-modal
      title="分配角色"
      v-model="setRoleModalVisible"
      @ok="saveRoleInfo()"
      @cancel="setRoleModalClosed()"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <a-select v-model="selectedRoleId" style="width:200px;">
            <a-select-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
              {{ item.roleName }}
            </a-select-option>
          </a-select>
        </p>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      userList: [],
      queryInfo: {
        query: '', // 查询参数
        pagenum: 1,
        pagesize: 2
      },
      pagination: {
        position: 'bottom',
        total: 0,
        current: 1,
        pageSize: 2,
        showSizeChanger: true,
        pageSizeOptions: ['1', '2', '5', '10', '20'],
        showTotal: total => `总共 ${total} 条`,
        onChange: (current, pageSize) => this.pageChange(current, pageSize),
        onShowSizeChange: (current, size) => this.showSizeChange(current, size)
      },
      columns: [
        { title: '序号', customRender: (text, record, index) => `${index + 1}` },
        { title: '姓名', dataIndex: 'username' },
        { title: '邮箱', dataIndex: 'email' },
        { title: '电话', dataIndex: 'mobile' },
        { title: '角色', dataIndex: 'role_name' },
        {
          title: '状态',
          dataIndex: 'mg_state',
          scopedSlots: { customRender: 'state' }
        },
        {
          title: '操作',
          width: '200px',
          dataIndex: 'id',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      addForm: {},
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      addModalVisible: false,
      editModalVisible: false,
      setRoleModalVisible: false,
      editForm: {},
      userInfo: [],
      rolesList: {},
      selectedRoleId: '',
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 发送请求获取用户数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.pagination.total = res.data.total
      this.pagination.current = this.queryInfo.pagenum
      this.pagination.pageSize = this.queryInfo.pagesize
    },
    // 搜索后跳转至第一页
    getSearchUserList() {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户信息失败')
        } else {
          this.$message.success('添加用户信息成功')
        }
        // 隐藏添加用户的对话框
        this.addModalVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 监听 current 当前页 pagesize页面大小 改变的事件
    pageChange(current, pageSize) {
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    // 改变每页显示条数
    showSizeChange(current, size) {
      this.queryInfo.pagesize = size
      this.pagination.pageSize = size
      this.getUserList()
    },
    // 改变状态
    async userStateChanged(record) {
      console.log(record)
      const { data: res } = await this.$http.put(
        `users/${record.id}/state/${record.mg_state}`
      )
      if (res.meta.status !== 200) {
        record.mg_state = !record.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 关闭添加用户对话框
    addModalClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 展示修改对话框
    async showEditModal(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
      this.editModalVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editModalClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        // 关闭对话框
        this.editModalVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },
    // 删除用户
    removeUserById(id) {
      const that = this
      this.$confirm({
        content: '此操作将永久删除该用户, 是否继续?',
        cancelText: '取消',
        okText: '确定',
        async onOk() {
          const { data: res } = await that.$http
            .delete(`users/${id}`)
            .catch(() => console.log('err'))
          if (res.meta.status !== 200) {
            return that.$message.error('删除用户失败')
          }
          that.$message.success('删除用户成功')
          that.getUserList()
        },
        onCancel() {
          that.$message.info('已经取消删除')
        }
      })
    },
    // 展示分配角色对话 框
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 展示对话框之前，获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      this.setRoleModalVisible = true
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有角色列表失败！！')
      }
      console.log(res.data)
      this.rolesList = res.data
    },
    // 点击按钮 确定更改角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色信息失败！')
      }
      this.$message.success('更新角色信息成功！')
      this.getUserList()
      this.setRoleModalVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleModalClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped></style>
